package com.fjp.heartguard.ui.splash

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.CacheUtil
import com.fjp.heartguard.databinding.ActivitySplashBinding
import com.fjp.heartguard.ui.login.LoginActivity
import com.fjp.heartguard.ui.main.MainActivity
import com.fjp.heartguard.viewmodel.SplashViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState

class SplashActivity : BaseActivity<SplashViewModel, ActivitySplashBinding>() {
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        lifecycleScope.launch {

            val userInfo = CacheUtil.getUser()
            if (CacheUtil.isLogin() && userInfo != null) {
                App.userInfo = userInfo
                mViewModel.getUserInfo()

            } else {
                delay(2000)
                startActivity(Intent(this@SplashActivity, LoginActivity::class.java))
                finish()
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.userInfo.observe(this) {
            parseState(it, {
                App.userInfo = it
                CacheUtil.setUser(it)
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                finish()
            }, {
                showToast(it.errorMsg)
                it.printStackTrace()
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                finish()
            })
        }
    }

}